#include "StdAfx.h"
#include "T2Entity.h"
#include "Wall.h"

namespace TSquare {
	using namespace System;

	Wall::Wall(PointF %start, PointF %end, float thickness) :
		start(start), end(end), thickness(thickness) {
		
		/*
		dy / dx = m
		dy = m . dx

		r . r = dx . dx + dy . dy
			  = dx . dx + m . dx . m . dx
			  = dx . dx . (1 + m . m)

		dx . dx = r . r / (1 + m . m)
		dx = root(r . r / (1 + m . m))
		*/

		float dy = end.Y - start.Y;
		float dx = end.X - start.X;

		float slope = dy / dx;
		float pslope = - 1 / slope;
		
		dx = (float) Math::Sqrt(thickness * thickness / (1 + pslope * pslope));
		dy = pslope * dx;
		startr.X = start.X + dx;
		startr.Y = start.Y + dy;

		endr.X = end.X + dx;
		endr.Y = end.Y + dy;
	}

	RectangleF Wall::GetBounds(){
		array<PointF> ^points = gcnew array<PointF>(4);
		points[0] = start;
		points[1] = startr;
		points[2] = end;
		points[3] = endr;

		RectangleF rv;
		rv.X = start.X;
		rv.Y = start.Y;
		rv.Width = 0;
		rv.Height = 0;

		PointF pmin = points[0], pmax = points[0];
		for(int i = 1; i < 4; i++){
			PointF% p = points[i];
			pmin.X = Math::Min(p.X, pmin.X);
			pmin.Y = Math::Min(p.Y, pmin.Y);
			pmax.X = Math::Max(p.X, pmax.X);
			pmax.Y = Math::Max(p.Y, pmax.Y);
		}

		return RectangleF::FromLTRB(pmin.X, pmin.Y, pmax.X, pmax.Y);
	}

	void Wall::Draw(Graphics ^g){
		g->DrawLine(Pens::Black, start, end);
		g->DrawLine(Pens::Black, end, endr);
		g->DrawLine(Pens::Black, endr, startr);
		g->DrawLine(Pens::Black, startr, start);
	}
}